package com.funymmz.demo.webapi;

import com.funymmz.demo.domain.Babyroom;
import com.funymmz.demo.service.BabyroomService;
import com.funymmz.demo.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/webapi/babyroom")
public class BabyroomRestController {

    @Autowired
    private BabyroomService babyroomService;

    /**
     * 获取所有母婴室信息
     *
     * @return 母婴室列表
     */
    @GetMapping("/list")
    public List<Babyroom> getAll() {
        return babyroomService.findAll();
    }

    /**
     * 带查询的分页
     *
     * @param page page
     * @param size size
     * @param name name
     * @return page
     */
    @GetMapping("/getByPage")
    public PageUtils getByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                               @RequestParam(value = "size", defaultValue = "10") Integer size,
                               @RequestParam(value = "name", defaultValue = "") String name) {
        //根据id排倒序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");

        Page<Babyroom> babyroomPage;
        if (StringUtils.isEmpty(name)) {
            Pageable pageable = PageRequest.of(page, size, sort);
            babyroomPage = babyroomService.findAll(pageable);
        } else {
            Babyroom babyroom = new Babyroom();
            babyroom.setName(name);

            Pageable pageable = PageRequest.of(0, 10, sort);
            //全模糊查询，即%{name}%
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Babyroom> example = Example.of(babyroom, matcher);
            babyroomPage = babyroomService.findAll(example, pageable);
        }
        return new PageUtils(babyroomPage.getContent(), babyroomPage.getTotalElements());
    }

    /**
     * 通过id获取母婴室
     *
     * @param id 母婴室Id号
     * @return 母婴室
     */
    @GetMapping("/get")
    public Babyroom getById(Long id) {
        return babyroomService.getById(id);
    }

    /**
     * 插入母婴室信息
     *
     * @param babyroom 母婴室
     * @return babyroom
     */
    @PostMapping("/insert")
    public Babyroom insert(Babyroom babyroom) {
        return babyroomService.insert(babyroom);
    }

    /**
     * 更新母婴室信息
     *
     * @param babyroom 母婴室
     * @return 母婴室
     */
    @PutMapping("/update")
    public Babyroom update(Babyroom babyroom) {
        return babyroomService.update(babyroom);
    }

    /**
     * 通过id删除母婴室
     *
     * @param id 母婴室Id号
     */
    @DeleteMapping("/delete")
    public void delete(Long id) {
        babyroomService.delete(id);
    }
}
